<template>
    <view class="pay-record-container">
        <!-- 记录列表 -->
        <view class="record-list">
            <view 
                v-for="(record, index) in payRecords" 
                :key="index"
                class="record-item"
            >
                <!-- 左侧信息 -->
                <view class="record-left">
                    <image src="https://puqinzc.oss-cn-beijing.aliyuncs.com/2bd05faf010b49049fd5232a15cd193f.png" mode="widthFix" class="record-icon"></image>
                    <view class="record-info">
                        <view class="record-title">{{ record.title }}</view>
                        <view class="record-time">{{ record.time }}</view>
                    </view>
                </view>

                <!-- 右侧状态 -->
                <view class="record-right">
                    <view 
                        v-if="record.invoiceState == 1" 
                        class="status-text waiting"
                        >
                        待开具
                    </view>
                    <view 
                        v-else-if="record.invoiceState == 2" 
                        class="status-text completed"
                        >
                        已开具
                    </view>
                    <view 
                        v-else 
                        class="status-btn pending"
                        @click="handleIssueInvoice(record)"
                    >
                        开发票
                    </view>
                </view>
            </view>
        </view>

        <!-- 加载更多状态 -->
        <view v-if="payRecords.length > 0" class="load-more">
            <view v-if="loading" class="loading-text">
                <text>加载中...</text>
            </view>
            <view v-else-if="hasMore" class="load-more-btn" @click="loadMore">
                <text>点击加载更多</text>
            </view>
            <view v-else class="no-more-text">
                <text>没有更多数据了</text>
            </view>
        </view>

        <!-- 空状态 -->
        <view v-if="payRecords.length === 0 && !loading" class="empty-state">
            <view class="empty-text">暂无缴费记录</view>
        </view>

        <!-- 开发票弹窗 -->
        <view class="register-popup" v-if="showInvoicePopup" @click="handleCloseInvoicePopup">
            <view class="popup-mask"></view>
            <view class="popup-content" @click.stop>
                <view class="popup-header">
                    <view class="popup-title">开发票</view>
                    <view class="popup-close" @click="handleCloseInvoicePopup">×</view>
                </view>
                <view class="popup-form">
                    <view class="form-item">
                        <view class="form-label">开票金额<text class="required">*</text></view>
                        <input class="form-input" v-model="invoiceForm.amount" placeholder="请输入" disabled />
                    </view>
                    <view class="form-item">
                        <view class="form-label">姓名<text class="required">*</text></view>
                        <input class="form-input" v-model="invoiceForm.name" placeholder="请输入" />
                    </view>
                    <view class="form-item">
                        <view class="form-label">身份证号<text class="required">*</text></view>
                        <input class="form-input" v-model="invoiceForm.idNo" placeholder="请输入" />
                    </view>
                    <view class="form-item">
                        <view class="form-label">联系电话<text class="required">*</text></view>
                        <input class="form-input" v-model="invoiceForm.phone" placeholder="请输入" type="number" />
                    </view>
                    <view class="form-item">
                        <view class="form-label">电子邮件<text class="required">*</text></view>
                        <input class="form-input" v-model="invoiceForm.email" placeholder="请输入" type="text" />
                    </view>
                </view>
                <view class="popup-footer">
                    <view class="primary-btn" @click="handleConfirmInvoice" :class="{ 'disabled': submitting }">
                        {{ submitting ? '提交中...' : '确认开发票' }}
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onShow, onReachBottom } from '@dcloudio/uni-app'
import { getOrderList, applyInvoice } from '../../utils/api.js'
import PaymentUtil from '../../utils/payment.js'

// 缴费记录数据
const payRecords = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(20)
const hasMore = ref(true)
const loading = ref(false)

// 开发票弹窗相关
const showInvoicePopup = ref(false)
const submitting = ref(false)
const currentRecord = ref(null)

// 开发票表单数据
const invoiceForm = ref({
    amount: '',
    name: '',
    idNo: '',
    phone: '',
    email: ''
})

// 页面显示时获取数据
onShow(() => {
    resetAndLoad()
})

// 上划到底部时加载更多
onReachBottom(() => {
    if (hasMore.value && !loading.value) {
        loadMore()
    }
})

// 重置并加载数据
const resetAndLoad = () => {
    currentPage.value = 1
    payRecords.value = []
    hasMore.value = true
    loadPayRecords()
}

// 加载更多
const loadMore = () => {
    if (hasMore.value && !loading.value) {
        currentPage.value++
        loadPayRecords(true)
    }
}

// 加载缴费记录
const loadPayRecords = async (isLoadMore = false) => {
    if (loading.value) return
    
    try {
        loading.value = true
        
        if (!isLoadMore) {
            uni.showLoading({ title: '加载中...' })
        }
        
        const userInfo = uni.getStorageSync('user_info') ? uni.getStorageSync('user_info') : {}
        const userId = userInfo.id
        
        if (!userId) {
            throw new Error('用户信息获取失败')
        }
        
        const result = await getOrderList({
            userId: userId,
            page: currentPage.value,
            size: pageSize.value
        })
        
        if (result.code == 0) {
            const newRecords = result.data.records.map(item => ({
                id: item.orderId || item.id,
                title: `会费缴纳${PaymentUtil.formatAmount(item.amount)}元`,
                time: item.createTime,
                invoiceState: item.invoiceState,
                orderData: item
            })) || []
            
            if (isLoadMore) {
                // 追加数据
                payRecords.value = [...payRecords.value, ...newRecords]
            } else {
                // 替换数据
                payRecords.value = newRecords
            }
            
            // 判断是否还有更多数据
            hasMore.value = newRecords.length === pageSize.value
            
        } else {
            throw new Error(result.message || '获取订单列表失败')
        }
        
    } catch (error) {
        console.error('加载缴费记录失败:', error)
        uni.showToast({
            title: error.message || '加载失败',
            icon: 'none'
        })
        
        // 如果是加载更多失败，回退页码
        if (isLoadMore) {
            currentPage.value--
        }
    } finally {
        loading.value = false
        uni.hideLoading()
    }
}

// 格式化时间
const formatTime = (timeStr) => {
    if (!timeStr) return ''
    const date = new Date(timeStr)
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hour = String(date.getHours()).padStart(2, '0')
    const minute = String(date.getMinutes()).padStart(2, '0')
    return `${month}-${day} ${hour}:${minute}`
}

// 获取状态文本
const getStatusText = (invoice_state) => {
    switch (invoice_state) {
        case 0:
            return 'pending' // 未开票，可以申请开发票
        case 1:
            return 'waiting' // 待开具
        case 2:
            return 'completed' // 已开具
        default:
            return 'pending'
    }
}

// 处理开发票
const handleIssueInvoice = (record) => {
    currentRecord.value = record
    // 设置开票金额
    invoiceForm.value.amount = PaymentUtil.formatAmount(record.orderData.amount)
    showInvoicePopup.value = true
}

// 关闭开发票弹窗
const handleCloseInvoicePopup = () => {
    showInvoicePopup.value = false
    // 重置表单数据
    invoiceForm.value = {
        amount: '',
        name: '',
        idNo: '',
        phone: '',
        email: ''
    }
    currentRecord.value = null
}

// 表单验证
const validateInvoiceForm = () => {
    if (!invoiceForm.value.amount) {
        uni.showToast({
            title: '开票金额不能为空',
            icon: 'none'
        })
        return false
    }
    if (!invoiceForm.value.name.trim()) {
        uni.showToast({
            title: '请输入姓名',
            icon: 'none'
        })
        return false
    }
    if (!invoiceForm.value.idNo.trim()) {
        uni.showToast({
            title: '请输入身份证号',
            icon: 'none'
        })
        return false
    }
    if (!invoiceForm.value.phone.trim()) {
        uni.showToast({
            title: '请输入联系电话',
            icon: 'none'
        })
        return false
    }
    if (!invoiceForm.value.email.trim()) {
        uni.showToast({
            title: '请输入电子邮件',
            icon: 'none'
        })
        return false
    }
    
    // 验证邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(invoiceForm.value.email)) {
        uni.showToast({
            title: '请输入正确的邮箱格式',
            icon: 'none'
        })
        return false
    }
    
    return true
}

// 确认开发票
const handleConfirmInvoice = async () => {
    // 表单验证
    if (!validateInvoiceForm()) {
        return
    }
    
    // 防止重复提交
    if (submitting.value) {
        return
    }
    
    submitting.value = true
    
    try {
        const invoiceData = {
            orderId: currentRecord.value.id,
            amount: currentRecord.value.orderData.amount,
            name: invoiceForm.value.name,
            idNo: invoiceForm.value.idNo,
            phone: invoiceForm.value.phone,
            email: invoiceForm.value.email
        }
        
        const result = await applyInvoice(invoiceData)
        
        if (result.code == 0) {
            // 更新记录状态
            if (currentRecord.value) {
                currentRecord.value.invoiceState = 1
            }
            
            uni.showToast({
                title: '申请成功',
                icon: 'success'
            })
            
            handleCloseInvoicePopup()
            
            // 刷新列表数据
            resetAndLoad()
        } else {
            throw new Error(result.message || '申请失败')
        }
        
    } catch (error) {
        console.error('申请开发票失败:', error)
        uni.showToast({
            title: error.message || '申请失败，请重试',
            icon: 'none'
        })
    } finally {
        submitting.value = false
    }
}
</script>

<style lang="scss" scoped>
.pay-record-container {
    min-height: 100vh;
    background: #F6F6F6;
    padding: 24rpx;

    .record-list {
        border: 2rpx solid #E7E8EB;
        background: #FFFFFF;
        border-radius: 16rpx;

        .record-item {
            padding: 32rpx 0;
            margin:0 24rpx;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 2rpx solid #E7E7E7;
            &:last-child {
                border-bottom: none;
            }

            .record-left {
                display: flex;
                align-items: center;
                flex: 1;

                .record-icon {
                    width: 56rpx;
                    height: 56rpx;
                    flex-shrink: 0;
                }

                .record-info {
                    margin-left: 16rpx;
                    flex: 1;

                    .record-title {
                        font-size: 28rpx;
                        color: rgba(0, 0, 0, 0.80);
                        line-height: 40rpx;
                        margin-bottom: 8rpx;
                    }

                    .record-time {
                        font-size: 24rpx;
                        color: rgba(0, 0, 0, 0.40);;
                        line-height: 34rpx;
                    }
                }
            }

            .record-right {
                .status-btn {
                    padding: 6rpx 16rpx;
                    border-radius: 24rpx;
                    font-size: 24rpx;
                    line-height: 32rpx;
                    text-align: center;
                    cursor: pointer;

                    &.pending {
                        background: #fff;
                        color: #005DF4;
                        border: 1rpx solid #005DF4;
                    }
                }

                .status-text {
                    font-size: 24rpx;
                    line-height: 32rpx;
                    padding: 12rpx 24rpx;
                    border-radius: 20rpx;

                    &.completed {
                        color: #0EBD70;
                    }

                    &.waiting {
                        color: #EBA800;
                    }
                }
            }
        }
    }

    .load-more {
        display: flex;
        justify-content: center;
        padding: 20rpx 0;
        font-size: 28rpx;
        color: #999;

        .loading-text {
            text-align: center;
        }

        .load-more-btn {
            color: #005DF4;
            text-decoration: underline;
            cursor: pointer;
        }

        .no-more-text {
            text-align: center;
        }
    }

    .empty-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding-top: 200rpx;

        .empty-icon {
            width: 120rpx;
            height: 120rpx;
            margin-bottom: 24rpx;
            opacity: 0.5;
        }

        .empty-text {
            font-size: 28rpx;
            color: #999999;
            line-height: 40rpx;
        }
    }

    // 开发票弹窗样式
    .register-popup {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 999;
        display: flex;
        align-items: flex-end;

        .popup-mask {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
        }

        .popup-content {
            position: relative;
            width: 100%;
            max-height: 85vh;
            min-height: 500rpx;
            background: #FFFFFF;
            border-radius: 24rpx 24rpx 0rpx 0rpx;
            z-index: 1000;
            display: flex;
            flex-direction: column;

            .popup-header {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 32rpx 24rpx 24rpx 24rpx;
                position: relative;
                flex-shrink: 0;
                border-bottom: 2rpx solid #f0f0f0;

                .popup-title {
                    position: absolute;
                    left: 50%;
                    transform: translateX(-50%);
                    font-size: 32rpx;
                    line-height: 44rpx;
                    font-weight: 500;
                    color: #000;
                    text-align: center;
                }

                .popup-close {
                    width: 48rpx;
                    height: 48rpx;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 40rpx;
                    color: rgba(0, 0, 0, 0.9);
                    cursor: pointer;
                    margin-left: auto;
                }
            }

            .popup-form {
                flex: 1;
                overflow-y: auto;
                padding: 0 24rpx;

                .form-item {
                    display: flex;
                    align-items: center;
                    padding: 24rpx 0;
                    border-bottom: 2rpx solid #E7E7E7;

                    &:last-child {
                        border-bottom: none;
                        padding-bottom: 32rpx;
                    }

                    .form-label {
                        width: 160rpx;
                        font-size: 28rpx;
                        color: #000;
                        flex-shrink: 0;

                        .required {
                            color: #FF4757;
                        }
                    }

                    .form-input {
                        flex: 1;
                        font-size: 28rpx;
                        color: #000;
                        border: none;
                        outline: none;
                        background: transparent;
                        
                        &:disabled {
                            color: #999;
                            background: #f5f5f5;
                        }
                    }
                }
            }

            .popup-footer {
                padding: 24rpx;
                flex-shrink: 0;
            }
        }
    }
}
</style>
